﻿using System;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace MVCPets.Extensions.MVC
{
  public static class HtmlHelperExtensions
  {
    public static string MenuItem(this HtmlHelper helper, string linkText, string actionName, string controllerName, bool IncludeSeparator)
    {
      var sb = new StringBuilder();

      if(IncludeSeparator) sb = sb.Append(GetSeparator());
      
      sb = sb.Append(GetMenuItem(helper, linkText, actionName, controllerName));

      return sb.ToString();
    }

    public static string MenuItem(this HtmlHelper helper, string linkText, string actionName, string controllerName)
    {
      return GetMenuItem(helper, linkText, actionName, controllerName);
    }

    private static string GetMenuItem(HtmlHelper helper, string linkText, string Action, string Controller)
    {
      var tb = new TagBuilder("li");

      if(IsSelected(helper, Action, Controller)) tb.Attributes.Add("class", "selected");

      tb.InnerHtml = helper.ActionLink(linkText, Action, Controller).ToString();
      
      return tb.ToString(TagRenderMode.Normal);
    }

    private static string GetSeparator()
    {
      var tb = new TagBuilder("li");

      tb.InnerHtml = "|";

      return tb.ToString(TagRenderMode.Normal);
    }

    private static bool IsSelected(HtmlHelper helper, string Action, string Controller)
    {
      string currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
      string currentActionName = (string)helper.ViewContext.RouteData.Values["action"];

      return currentControllerName.Equals(Controller, StringComparison.CurrentCultureIgnoreCase)
        && currentActionName.Equals(Action, StringComparison.CurrentCultureIgnoreCase);

    }
  }
}
